var express = require('express');
var router = express.Router();
var { CateModel, GoodModel,CouponModel } = require('../model/limengxi')
/* GET users listing. */
// router.get('/', function (req, res, next) {
//   res.send('respond with a resource');
// });

// 创建分类
router.post('/addcate', async (req, res) => {
    let obj = req.body
    await CateModel.create(obj)
    res.send({
        code: 200,
        msg: '添加成功'
    })
})
// 获取分类
router.get('/getcate', async (req, res) => {
    let data = await CateModel.find()
    res.send({
        code: 200,
        msg: '获取成功',
        data
    })
})
// 新增商品
router.post('/addgood', async (req, res) => {
    let obj = req.body
    await GoodModel.create(obj)
    res.send({
        code: 200,
        msg: '添加成功'
    })
})
// 分类页面获取商品
router.get('/getgoods', async (req, res) => {
    let { cateid } = req.query
    console.log(cateid);
    let data = await GoodModel.find({ cate: cateid })

    let categorizedData = {};

    data.forEach(item => {
        if (!categorizedData[item.subCategory]) {
            categorizedData[item.subCategory] = [];
        }
        categorizedData[item.subCategory].push(item);
    });
    let arr = []
    for (const [key, value] of Object.entries(categorizedData)) {
        // console.log(`${key}: ${value}`);
        arr.push({
            subCategory: key,
            goods: value
        })
    }
    //   console.log(arr);
    res.send({
        code: 200,
        msg: '获取成功',
        arr
    })
})
// 搜索页面搜索商品
router.get('/searchgoods', async (req, res) => {
    let { goodsname } = req.query
    let data = await GoodModel.find({ name: { $regex: goodsname } })
    res.send({
        code: 200,
        msg: '获取成功',
        data
    })
})

// 获取优惠卷
router.get('/getcoupon', async (req, res) => {
    let data = await CouponModel.find()
    res.send({
        code: 200,
        msg: '获取成功',
        data
    })
})
module.exports = router;
